package com.baizhi.log;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.entrty.Admin;
import com.baizhi.entrty.Log;
import com.baizhi.service.AdminService;
import com.baizhi.service.LogService;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAspect {
    @Autowired
    private LogService ls;

    @Autowired
    private AdminService as;

    private Logger logger = LoggerFactory.getLogger(LogAnnotation.class);

    @Pointcut("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logPoincut(){}


    @After("logPoincut()")
    public void logAfter(JoinPoint joinPoint){
        Log log = new Log();
        log.setLogDate(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = attributes.getRequest().getSession();
        Admin user = (Admin) session.getAttribute("user");
        String username = user.getUsername();
        log.setAdminName(username);

        String ipAddrByRequest = IPKit.getIpAddrByRequest(attributes.getRequest());
        log.setLogIp(ipAddrByRequest);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String value = annotation.value();
        log.setLogContent(value);

        logger.info("user"+log);
        logger.info("user"+log);
        logger.info("user"+log);
        logger.info("user"+log);
        ls.insert(log);


    }

}
